﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.UI.WebControls;
using umbraco.BasePages;

namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class EditNewsletterCampaign : System.Web.UI.Page
    {
        private int _id;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["campaignId"] = "";
                _id = int.Parse(Request["id"]);
                Literal1.Text = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<string>("select alias from newsLetterCampaign where id = @id",
                                                                                                  umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", _id));

                var connectionString = umbraco.BusinessLogic.Application.SqlHelper.ConnectionString;
                string selectSql;
                switch (_id)
                {
                    case 1:
                        selectSql = "SELECT * FROM newsLetterCampaignNewsletter";
                        break;
                    case 2:
                        selectSql = "SELECT * FROM newsLetterCampaignNewsletter where campstatus='draft' or campstatus='delayed'";
                        break;
                    default:
                        selectSql = "SELECT * FROM newsLetterCampaignNewsletter where campstatus='sent'";
                        break;
                }
                selectSql += " ORDER BY id DESC";
                var con = new SqlConnection(connectionString);
                var cmd = new SqlCommand(selectSql, con);
                var adapter = new SqlDataAdapter(cmd);
                var ds = new DataSet();

                adapter.Fill(ds);

                Repeater1.DataSource = ds;
                Repeater1.ItemDataBound += Repeater1_ItemDataBound;
                Repeater1.DataBind();

                //for (int i = 0; i < Repeater1.Items.Count; i++)
                //{
                //    var lt = (Literal)Repeater1.Items[i].FindControl("LiteralEmail");
                //    var btEdit = (Button)Repeater1.Items[i].FindControl("btnEdit");
                //    var campaignId = Convert.ToInt32(btEdit.CommandArgument);

                //    var numRecipients = 0;
                //    var numSentTo = 0;

                //    var ltStatus = (Literal)Repeater1.Items[i].FindControl("LiteralStatus");
                //    if (ltStatus.Text == "sent" || ltStatus.Text == "sending")
                //    {
                //        var btView = (Button)Repeater1.Items[i].FindControl("btnReport");
                //        btView.Visible = true;
                //        btEdit.Visible = false;
                //        var btDelete = (Button)Repeater1.Items[i].FindControl("btnDelete");
                //        btDelete.Visible = false;
                //        numSentTo = Bll.Helper.GetNumberOfMembersSentTo(campaignId);
                //        if (ltStatus.Text == "sent")
                //        {
                //            numRecipients =
                //                umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(
                //                    "SELECT count(id) FROM newsLetterSendMail WHERE campaignId = @campaignId",
                //                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId",
                //                                                                                campaignId));
                //        }
                //        else if(ltStatus.Text == "sending")
                //        {
                //            numRecipients = Bll.Helper.GetMembersForCampaign(campaignId).Count;
                //        }
                //    }
                //    else
                //    {
                //        numRecipients = Bll.Helper.GetMembersForCampaign(campaignId).Count;
                //    }
                //    lt.Text = string.Format("{0}/{1}", numSentTo, numRecipients);
                //}

            }

        }

        void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var lt = (Literal) e.Item.FindControl("LiteralEmail");
                var btEdit = (Button) e.Item.FindControl("btnEdit");
                var campaignId = Convert.ToInt32(btEdit.CommandArgument);

                var numRecipients = 0;
                var numSentTo = 0;

                var ltStatus = (Literal) e.Item.FindControl("LiteralStatus");
                if (ltStatus.Text == "sent" || ltStatus.Text == "sending")
                {
                    var btView = (Button) e.Item.FindControl("btnReport");
                    btView.Visible = true;
                    btEdit.Visible = false;
                    var btDelete = (Button) e.Item.FindControl("btnDelete");
                    btDelete.Visible = false;
                    numSentTo = Bll.Helper.GetNumberOfMembersSentTo(campaignId);
                    if (ltStatus.Text == "sent")
                    {
                        numRecipients =
                            umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(
                                "SELECT count(id) FROM newsLetterSendMail WHERE campaignId = @campaignId",
                                umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId",
                                                                                            campaignId));
                    }
                    else if (ltStatus.Text == "sending")
                    {
                        numRecipients = Bll.Helper.GetMembersForCampaign(campaignId).Count;
                    }
                }
                else
                {
                    numRecipients = Bll.Helper.GetMembersForCampaign(campaignId).Count;
                }
                lt.Text = string.Format("<span class=\"numSentTo\">{0}</span>/{1}", numSentTo, numRecipients);
            }
        }



        protected void Repeater1_OnItemCommand(object source, RepeaterCommandEventArgs e)
        {
            var btnDelete = (Button)e.Item.FindControl("btnDelete");
            var btEdit = (Button)e.Item.FindControl("btnEdit");
            var btCopy = (Button)e.Item.FindControl("btnCopy");

            if (String.Equals(e.CommandName, "Delete"))
            {
                //remove relationship between group and campaign
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsLetterCampaign2Group where campaignId=@campaignId",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));

                //remove campaign
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsletterCampaignNewsletter where id=@campaignId",
                                                                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));

                //remove any possible delayed references
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery("delete from newsLetterCampaignDelayedSend where campaignId=@campaignId",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campaignId", btnDelete.CommandArgument));
                _id = int.Parse(Request["id"]);
                Response.Redirect("editNewsletterCampaign.aspx?id=" + _id);
            }
            else if (String.Equals(e.CommandName, "Edit"))
            {
                Session["campaignId"] = btEdit.CommandArgument;
                Response.Redirect("createNewsletterCampaign.aspx");

            }
            else if (String.Equals(e.CommandName, "Copy"))
            {
                var newId = -1;
                //copy campaign
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsletterCampaignNewsletter where id=@id",
                                                                              umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btCopy.CommandArgument)))
                {
                    while (reader.Read())
                    {
                        newId = umbraco.BusinessLogic.Application.SqlHelper.ExecuteScalar<int>(
                            "insert into newsletterCampaignNewsletter(camptitle, campsubject, campstatus, campfrom, campreplyMail, campTemplate, campContent, campTemplatecontent, campTrack, campGoogle) values(@title, @subject, @status, @from, @replyMail, @Template, @Content, @campTemplatecontent, @campTrack, @campGoogle); select @@Identity",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@title",
                                                                                        reader.GetString("camptitle")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@subject",
                                                                                        reader.GetString("campstatus")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@status", "draft"),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@from",
                                                                                        reader.GetString("campfrom")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@replyMail",
                                                                                        reader.GetString("campreplyMail")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Template",
                                                                                        reader.GetString("campTemplate")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@Content",
                                                                                        reader.GetString("campContent")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTemplatecontent",
                                                                                        reader.GetString(
                                                                                            "campTemplatecontent")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campTrack",
                                                                                        reader.GetString("campTrack")),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@campGoogle",
                                                                                        reader.GetString("campGoogle")));

                    }
                }

                //copy campaign2group relationship
                using (var reader =
                    umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaign2Group where campaignId=@id",
                                                                              umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", btCopy.CommandArgument)))
                {
                    while (reader.Read())
                    {
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                            "insert into newsLetterCampaign2Group(campaignId, groupName) values(@id, @name);",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", newId),
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@name",
                                                                                        reader.GetString("groupName")));
                    }
                }

                _id = int.Parse(Request["id"]);
                Response.Redirect("editNewsletterCampaign.aspx?id=" + _id);
            }
            else if (String.Equals(e.CommandName, "View"))
            {
                var sb = new StringBuilder();
                sb.AppendLine(@"<script type=""text/javascript"">");
                sb.AppendLine(ClientTools.Scripts.OpenModalWindow("/umbraco/plugins/designit/newsletter/report.aspx?id=" + btEdit.CommandArgument, "View report", 608, 500));
                sb.AppendLine("</script>");
                Page.ClientScript.RegisterStartupScript(GetType(), "viewReport", sb.ToString());
            }
        }
    }
}